package com.blankii.androidlibrary.ui

import android.view.View
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * author: blankii
 * created on: 2025/7/9 16:46
 * description: 已做安全筛选
 */
object ViewShanManager {
    private val viewIdWithJobMap = HashMap<Int, Job>()

    /**
     * 使一个view闪烁
     * view:需要闪烁的view对象
     * looper: true=一直闪烁
     * maxCount:闪烁的最大次数，配合looper=false
     *
     * 如果处于关闭状态，则开启并返回Job
     * 如果已经处于打开状态，则返回null
     */
    fun open(view: View, looper: Boolean = false, maxCount: Int = 4) {
        if (viewIdWithJobMap.contains(view.id)) {
            //已打开
            return
        } else {
            //未开启的话开启
            val job = startWork(view, looper, maxCount)
            viewIdWithJobMap[view.id] = job
        }
    }

    /**
     * 结束闪灯
     */
    fun close(view: View) {
        if (viewIdWithJobMap.contains(view.id)) {
            viewIdWithJobMap[view.id]!!.job.cancel()
            viewIdWithJobMap.remove(view.id)
        }
    }

    private fun startWork(view: View, looper: Boolean = false, maxCount: Int = 4): Job {
        var count = 0//闪烁次数
        return CoroutineScope(Dispatchers.IO).launch {
            while (looper || count < maxCount) {
                withContext(Dispatchers.Main) {
                    view.visibility = View.VISIBLE
                }
                delay(400)
                withContext(Dispatchers.Main) {
                    view.visibility = View.INVISIBLE
                }
                delay(400)
                count++
            }
            withContext(Dispatchers.Main) {
                view.visibility = View.VISIBLE
            }
            //执行结束的话，比如looper=false,自动清除
            viewIdWithJobMap.remove(view.id)
        }
    }

    fun isShan(view: View): Boolean {
        return viewIdWithJobMap.contains(view.id)
    }


}